package com.test.quartz.controller;

import com.test.quartz.memory.job.Job1;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/jdbc")
public class JdbcController {

    @Autowired
    private Scheduler scheduler;

    /**
     * 添加任务
     */
    @RequestMapping("/add")
    public String add(){
        JobDetail jodDetail = JobBuilder.newJob(Job1.class)
                .withIdentity("job1", "group1")
                .storeDurably()
                .build();

        Trigger trigger = TriggerBuilder.newTrigger()
                .withIdentity("trigger1", "group1")
                .forJob(jodDetail)
                .startNow()
                .withSchedule(CronScheduleBuilder.cronSchedule("0/3 * * * * ?"))
                .build();
        try {
            scheduler.scheduleJob(jodDetail, trigger);
        } catch (SchedulerException e) {
            e.printStackTrace();
            return "fail:"+e.getMessage();
        }
        return "success";
    }


    @RequestMapping("/pause")
    public String test3() throws SchedulerException {
        JobKey jobKey = new JobKey("job1", "group1");
        JobDetail jobDetail = scheduler.getJobDetail(jobKey);
        if (jobDetail == null){
            return "job1 不存在";
        }else {
            scheduler.pauseJob(jobKey);
            return "job1 暂停成功";
        }
    }

    @RequestMapping("/resume")
    public String test4() throws SchedulerException {
        JobKey jobKey = new JobKey("job1", "group1");
        JobDetail jobDetail = scheduler.getJobDetail(jobKey);
        if (jobDetail == null){
            return "job1 不存在";
        }else {
            scheduler.resumeJob(jobKey);
            return "job1 恢复成功成功";
        }
    }


    @RequestMapping("/delete")
    public String delete() throws SchedulerException {
        JobKey jobKey = new JobKey("job1", "group1");
        JobDetail jobDetail = scheduler.getJobDetail(jobKey);
        if (jobDetail == null){
            return "job1 不存在";
        }else {
            scheduler.deleteJob(jobKey);
            return "job1 删除成功";
        }
    }



}
